package com.lcu.bos.web.realm;

import com.lcu.bos.dao.IUserDao;
import com.lcu.bos.modle.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class BOSRealm extends AuthorizingRealm {
    @Autowired
    private IUserDao userDao;
    @Override
    /**
     *  权限-与角色相关
     *  权限管理
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //根据用户ID查权限
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermission("staff");
        info.addRole("staff");
        return info;
    }

    /**
     *   登陆认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("doGetAuthenticationInfo:"+token);
        //查询数据放在realm中
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        //获取用户名
        String username = upToken.getUsername();

        //2.根据名字查找用户
        User dbUser=userDao.findByUsername(username);
        if(dbUser!=null){
            /*
            * Object principal;把数据库查询的对象
              Object credentials;写密码自动验证，查询出来的密码
              String realmName,当前类名;
            * */
            //返回AuthenticationInfo对象  内部会与token自动校验密码
            AuthenticationInfo info=new SimpleAuthenticationInfo(dbUser,
                    dbUser.getPassword(),
                    this.getClass().getName());
            return info;
        }
        return null;
    }
}
